const Settings = require("../models/settings.model");
const User = require("../models/user.model");
const settingsService = require("../services/settings.service");
const bcrypt = require("bcryptjs");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

// 配置文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = "uploads/avatars";
    // 确保上传目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, `avatar-${uniqueSuffix}${path.extname(file.originalname)}`);
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 2 * 1024 * 1024, // 限制 2MB
  },
  fileFilter: function (req, file, cb) {
    const allowedTypes = ["image/jpeg", "image/png", "image/gif"];
    if (!allowedTypes.includes(file.mimetype)) {
      cb(new Error("只允许上传 JPG、PNG、GIF 格式的图片"));
      return;
    }
    cb(null, true);
  },
}).single("file");

// 测试邮件通知
exports.testEmailNotification = async (req, res) => {
  try {
    settingsService.testEmailNotification(req.user._id);
    // 暂时返回成功
    res.json({ message: "邮件功能未启用" });
  } catch (error) {
    res.status(500).json({ error: "发送测试邮件失败" });
  }
};

// 获取设置
exports.getSettings = async (req, res) => {
  try {
    console.log("Getting settings for user:", req.user._id);

    // 使用 getOrCreate 静态方法获取或创建设置
    const settings = await Settings.getOrCreate(req.user._id);

    // 确保返回的数据结构符合前端期望
    const response = {
      interface: {
        theme: {
          mode: settings.interface?.theme?.mode || "light",
          primaryColor: settings.interface?.theme?.primaryColor || "#1a5cff",
          compact: settings.interface?.theme?.compact || false,
          animations: settings.interface?.theme?.animations || true,
        },
        timezone: settings.interface?.timezone || "Asia/Shanghai",
      },
      notifications: {
        deployStart: settings.notifications?.deployStart ?? true,
        deployComplete: settings.notifications?.deployComplete ?? true,
        deployFailed: settings.notifications?.deployFailed ?? true,
        channels: {
          browser: settings.notifications?.channels?.browser || false,
          email: settings.notifications?.channels?.email || false,
        },
      },
    };

    console.log("Sending settings response:", response);
    res.json(response);
  } catch (error) {
    console.error("Error getting settings:", error);
    res.status(500).json({
      error: "获取设置失败",
      message: error.message,
      stack: process.env.NODE_ENV === "development" ? error.stack : undefined,
    });
  }
};

// 更新设置
exports.updateSettings = async (req, res) => {
  try {
    const { section, data } = req.body;
    console.log("Updating settings:", { section, data, userId: req.user._id });

    // 验证 section 是否合法
    const validSections = ["interface", "notifications", "deployment"];
    if (!validSections.includes(section)) {
      return res.status(400).json({ error: "无效的设置类型" });
    }

    // 使用 getOrCreate 获取或创建设置
    let settings = await Settings.getOrCreate(req.user._id);

    // 根据 section 更新相应部分
    if (section === "interface") {
      settings.interface = {
        ...settings.interface,
        ...data,
      };
    } else if (section === "notifications") {
      settings.notifications = {
        ...settings.notifications,
        ...data,
      };
    } else if (section === "deployment") {
      settings.deployment = {
        ...settings.deployment,
        ...data,
      };
    }

    await settings.save();

    // 返回更新后的完整设置
    const response = {
      interface: settings.interface,
      notifications: settings.notifications,
      deployment: settings.deployment,
    };

    console.log("Settings updated successfully:", response);
    res.json(response);
  } catch (error) {
    console.error("Error updating settings:", error);
    res.status(500).json({
      error: "更新设置失败",
      message: error.message,
      stack: process.env.NODE_ENV === "development" ? error.stack : undefined,
    });
  }
};

// 更新个人信息
exports.updateProfile = async (req, res) => {
  try {
    const { username, email } = req.body;
    console.log("Updating profile:", { username, email });

    // 检查邮箱是否已被使用
    const existingUser = await User.findOne({
      email,
      _id: { $ne: req.user._id },
    });

    if (existingUser) {
      return res.status(400).json({ error: "该邮箱已被使用" });
    }

    const user = await User.findByIdAndUpdate(
      req.user._id,
      { username, email },
      { new: true }
    ).select("-password");

    res.json(user);
  } catch (error) {
    console.error("Error updating profile:", error);
    res.status(500).json({
      error: "更新个人信息失败",
      message: error.message,
    });
  }
};

// 更新密码
exports.updatePassword = async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    const user = await User.findById(req.user._id);

    const isMatch = await bcrypt.compare(currentPassword, user.password);
    if (!isMatch) {
      return res.status(400).json({ error: "当前密码错误" });
    }

    user.password = await bcrypt.hash(newPassword, 10);
    await user.save();

    res.json({ message: "密码已更新" });
  } catch (error) {
    console.error("Error updating password:", error);
    res.status(500).json({
      error: "更新密码失败",
      message: error.message,
    });
  }
};

// 获取登录设备
exports.getLoginDevices = async (req, res) => {
  try {
    const settings = await Settings.findOne({ userId: req.user._id });
    const devices = settings?.loginDevices.filter((d) => d.isActive) || [];

    // 添加当前设备
    const currentDevice = {
      id: "current",
      name: "当前设备",
      type: "browser",
      ip: req.ip,
      lastLogin: new Date(),
      current: true,
    };

    res.json([currentDevice, ...devices]);
  } catch (error) {
    console.error("Error getting login devices:", error);
    res.status(500).json({
      error: "获取登录设备失败",
      message: error.message,
    });
  }
};

// 登出设备
exports.logoutDevice = async (req, res) => {
  try {
    const { deviceId } = req.params;
    const settings = await Settings.findOne({ userId: req.user._id });

    if (!settings) {
      return res.status(404).json({ error: "设置不存在" });
    }

    await settings.removeLoginDevice(deviceId);
    res.json({ message: "设备已登出" });
  } catch (error) {
    console.error("Error logging out device:", error);
    res.status(500).json({
      error: "登出设备失败",
      message: error.message,
    });
  }
};

// 导出设置
exports.exportSettings = async (req, res) => {
  try {
    const settings = await Settings.findOne({ userId: req.user._id });
    res.json(settings);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 导入设置
exports.importSettings = async (req, res) => {
  try {
    const settings = req.body;
    await Settings.findOneAndUpdate({ userId: req.user._id }, settings, {
      new: true,
      upsert: true,
    });
    res.json({ message: "设置导入成功" });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

// 上传头像
exports.uploadAvatar = async (req, res) => {
  upload(req, res, async function (err) {
    if (err instanceof multer.MulterError) {
      return res
        .status(400)
        .json({ error: "文件上传错误", message: err.message });
    } else if (err) {
      return res
        .status(400)
        .json({ error: "文件上传失败", message: err.message });
    }

    try {
      if (!req.file) {
        return res.status(400).json({ error: "没有上传文件" });
      }

      // 生成文件的访问URL
      const fileUrl = `${
        process.env.API_URL || "http://localhost:3000"
      }/uploads/avatars/${req.file.filename}`;

      // 更新用户头像URL
      const updatedUser = await User.findByIdAndUpdate(
        req.user._id,
        { avatarUrl: fileUrl },
        { new: true }
      ).select("-password");

      // 确保返回完整的响应
      res.json({
        url: fileUrl,
        message: "头像上传成功",
        user: updatedUser,
      });
    } catch (error) {
      console.error("Error uploading avatar:", error);
      res.status(500).json({
        error: "头像上传失败",
        message: error.message,
      });
    }
  });
};
